package com.sky.business.sys.handler.endpoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.business.sys.domain.CameraConfig;
import com.sky.business.sys.domain.SystemConfig;
import com.sky.business.sys.event.ExtendCameraStatus;
import com.sky.business.sys.event.HeartbeatEvent;
import com.sky.business.sys.handler.MqttEventHandler;
import com.sky.business.sys.service.CameraConfigService;
import com.sky.business.sys.service.SystemConfigService;
import com.sky.business.sys.util.MQTTClientUtils;
import com.sky.common.config.CacheConstants;
import com.sky.common.track.DeviceStatus;
import com.sky.common.track.TrackTaskManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.SimpleTimeZone;

/**
 * 设备心跳事件处理器
 */
@Slf4j
@Component
public class CameraHeartbeatEventHandler implements MqttEventHandler {

    @Autowired
    private CameraConfigService cameraConfigService;

    @Autowired
    private SystemConfigService systemConfigService;

    public static final ObjectMapper objectMapper = new ObjectMapper().setTimeZone(SimpleTimeZone.getTimeZone("GMT+8"));


    @Override
    public boolean match(String topic, String msg, String event) {
        return "HeartBeat".equals(event);
    }

    @Override
    public void handle(String topic, String msg) throws Exception{
        SystemConfig  systemConfig = systemConfigService.getSystemConfig();
        HeartbeatEvent event = objectMapper.readValue(msg, HeartbeatEvent.class);
        HeartbeatEvent.Metadata metadata = event.getMetadata();
        CameraConfig cameraConfig = cameraConfigService.findByDeviceId(metadata.getDeviceId());
        Date now = new Date();
        if(cameraConfig!=null){
            //更新设备状态
            ExtendCameraStatus cameraStatus = event.getMetadata().getCameraStatus();
            DeviceStatus deviceStatus = TrackTaskManager.getDeviceStatus(metadata.getDeviceId());
            deviceStatus.setLastPanOrientAngle(cameraStatus.getPanOrientAngle().doubleValue());
            deviceStatus.setLastTiltOrientAngle(cameraStatus.getTiltOrientAngle().doubleValue());
            deviceStatus.setLastWorkState(event.getMetadata().getWorkState());
            deviceStatus.setLastHeartbeat(now);
            if (metadata.getWorkState() == CacheConstants.PROACTIVE_WORK_STATE) {
                deviceStatus.setLastOeTaskTime(now);
            }else{
                deviceStatus.setLastTrackingTaskId(metadata.getTaskId());
            }
        }else{
            log.error("设备不存在,deviceId:{}",metadata.getDeviceId());
        }
        MQTTClientUtils.publish(MQTTClientUtils.CMCC_MQTT_CLIENT,  systemConfig.getCmccReportingTopic(),  0, msg);
    }
}
